Coiteration¶
🎨 range
¶
In [1]:
print(range(5))
range(0, 5)
In [3]:
print(list(range(7)))
[0, 1, 2, 3, 4, 5, 6]
In [4]:
for i in range(5):
print(i)
0 1 2 3 4
🎨 zip
¶
In [5]:
names = ['John', 'Juan', 'João', 'Giovanni']
ages = [23, 18, 24, 22]
zip(names, ages)
Out[5]:
<zip at 0x105af6700>
🤨
In [6]:
names = ['John', 'Juan', 'João', 'Giovanni']
ages = [23, 18, 24, 22]
list(zip(names, ages))
Out[6]:
[('John', 23), ('Juan', 18), ('João', 24), ('Giovanni', 22)]
In [7]:
names = ['John', 'Juan', 'João', 'Giovanni']
ages = [23, 18, 24, 22]
for name, age in zip(names, ages):
print(f'{name} is {age} years old')
John is 23 years old Juan is 18 years old João is 24 years old Giovanni is 22 years old
In [8]:
names = ['John', 'Juan', 'João', 'Giovanni']
ages = [23, 18, 24, 22]
majors = ['Chemistry', 'Animation', 'Sociology', 'Secondary Education']
for name, age, major in zip(names, ages, majors):
print(f'{name} is {age} years old and studies {major}')
John is 23 years old and studies Chemistry Juan is 18 years old and studies Animation João is 24 years old and studies Sociology Giovanni is 22 years old and studies Secondary Education
In [9]:
fruits = ['apple', 'pear', 'blueberry', 'grape', 'strawberry']
plant_types = ['tree', 'tree', 'bush', 'vine']
for fruit, plant_type in zip(fruits, plant_types):
print(f'The {fruit} grows on a {plant_type}.')
The apple grows on a tree. The pear grows on a tree. The blueberry grows on a bush. The grape grows on a vine.
In [10]:
word1 = 'planter'
word2 = 'started'
for letter1, letter2 in zip(word1, word2):
if letter1 == letter2:
print(f'{letter1} == {letter2} ✅')
else:
print(f'{letter1} != {letter2}')
p != s l != t a == a ✅ n != r t == t ✅ e == e ✅ r != d
In [13]:
items = ['apple', 'banana', 'cherry', 'date']
for i, item in zip(range(len(items)), items):
print(f'{i}: {item}')
0: apple 1: banana 2: cherry 3: date
🎨 enumerate
¶
In [14]:
enumerate(['Paula', 'Patty', 'Peter', 'Peregrin'])
Out[14]:
<enumerate at 0x105850630>
In [15]:
list(enumerate(['Paula', 'Patty', 'Peter', 'Peregrin']))
Out[15]:
[(0, 'Paula'), (1, 'Patty'), (2, 'Peter'), (3, 'Peregrin')]
In [16]:
for index, name in enumerate(['Paula', 'Patty', 'Peter', 'Peregrin']):
print(f'{index}: {name}')
0: Paula 1: Patty 2: Peter 3: Peregrin
Key Ideas¶
- To get a sequence from 0 to a number, use
range
- To iterate through multiple things at the same time, use
zip
- To get the index along with the item while iterating, use
enumerate